
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>基于类的视图 &#8212; Django 3.2.11.dev 文档</title>
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <script type="text/javascript" src="../../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../../genindex.html" />
    <link rel="search" title="搜索" href="../../search.html" />
    <link rel="next" title="基于类的视图" href="intro.html" />
    <link rel="prev" title="模板" href="../templates.html" />



 
<script src="../../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../index.html">Django 3.2.11.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../index.html">Home</a>  |
        <a title="Table of contents" href="../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../genindex.html">Index</a>  |
        <a title="Module index" href="../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="../templates.html" title="模板">previous</a>
     |
    <a href="../index.html" title="使用 Django" accesskey="U">up</a>
   |
    <a href="intro.html" title="基于类的视图">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="topics-class-based-views-index">
            
  <div class="section" id="s-class-based-views">
<span id="class-based-views"></span><h1>基于类的视图<a class="headerlink" href="#class-based-views" title="永久链接至标题">¶</a></h1>
<p>视图是可调用的，能接受用户的请求并返回响应。视图远不只是个函数，Django提供了一些可用作视图的类的示例，允许你通过继承和复用构建自己的视图并且复用这些代码。虽然接下来还会介绍一些用于任务的通用视图，但你可能想自己设计可复用的视图结构，以便针对某些特殊场景。详情请见 class-based views reference documentation&lt;/ref/class-based-views/index&gt; 。</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="intro.html">基于类的视图</a></li>
<li class="toctree-l1"><a class="reference internal" href="generic-display.html">内置的基于类的通用视图</a></li>
<li class="toctree-l1"><a class="reference internal" href="generic-editing.html">使用基于类的视图处理表单</a></li>
<li class="toctree-l1"><a class="reference internal" href="mixins.html">在基于类的视图中使用混入</a></li>
</ul>
</div>
<div class="section" id="s-basic-examples">
<span id="basic-examples"></span><h2>基础示例<a class="headerlink" href="#basic-examples" title="永久链接至标题">¶</a></h2>
<p>Django 提供了适用于很多应用的基本视图类。所有视图继承自  <a class="reference internal" href="../../ref/class-based-views/base.html#django.views.generic.base.View" title="django.views.generic.base.View"><code class="xref py py-class docutils literal notranslate"><span class="pre">View</span></code></a> 类，它处理视图链接到 URLs，HTTP 方法调度和其他简单功能。<a class="reference internal" href="../../ref/class-based-views/base.html#django.views.generic.base.RedirectView" title="django.views.generic.base.RedirectView"><code class="xref py py-class docutils literal notranslate"><span class="pre">RedirectView</span></code></a> 用于 HTTP 重定向，<a class="reference internal" href="../../ref/class-based-views/base.html#django.views.generic.base.TemplateView" title="django.views.generic.base.TemplateView"><code class="xref py py-class docutils literal notranslate"><span class="pre">TemplateView</span></code></a> 扩展基类来使它能渲染模板。</p>
</div>
<div class="section" id="s-usage-in-your-urlconf">
<span id="usage-in-your-urlconf"></span><h2>在 URLconf 中的用法<a class="headerlink" href="#usage-in-your-urlconf" title="永久链接至标题">¶</a></h2>
<p>使用通用视图最直接的方式是在 URLconf 中直接创建它们。如果你只在基于类的视图上改变一些属性，那么你可以把它们传递到 <a class="reference internal" href="../../ref/class-based-views/base.html#django.views.generic.base.View.as_view" title="django.views.generic.base.View.as_view"><code class="xref py py-meth docutils literal notranslate"><span class="pre">as_view()</span></code></a> 方法中调用：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.urls</span> <span class="kn">import</span> <span class="n">path</span>
<span class="kn">from</span> <span class="nn">django.views.generic</span> <span class="kn">import</span> <span class="n">TemplateView</span>

<span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
    <span class="n">path</span><span class="p">(</span><span class="s1">&#39;about/&#39;</span><span class="p">,</span> <span class="n">TemplateView</span><span class="o">.</span><span class="n">as_view</span><span class="p">(</span><span class="n">template_name</span><span class="o">=</span><span class="s2">&quot;about.html&quot;</span><span class="p">)),</span>
<span class="p">]</span>
</pre></div>
</div>
<p>任何传递到 <a class="reference internal" href="../../ref/class-based-views/base.html#django.views.generic.base.View.as_view" title="django.views.generic.base.View.as_view"><code class="xref py py-meth docutils literal notranslate"><span class="pre">as_view()</span></code></a>&nbsp; 的参数将覆盖在类上设置的属性。在这个例子中，我们在 <code class="docutils literal notranslate"><span class="pre">TemplateView</span></code> 上设置 <code class="docutils literal notranslate"><span class="pre">template_name</span></code> 。一个相似的覆盖模式可用于 <a class="reference internal" href="../../ref/class-based-views/base.html#django.views.generic.base.RedirectView" title="django.views.generic.base.RedirectView"><code class="xref py py-class docutils literal notranslate"><span class="pre">RedirectView</span></code></a> 上的 <code class="docutils literal notranslate"><span class="pre">url</span></code> 属性。</p>
</div>
<div class="section" id="s-subclassing-generic-views">
<span id="subclassing-generic-views"></span><h2>子类化通用视图<a class="headerlink" href="#subclassing-generic-views" title="永久链接至标题">¶</a></h2>
<p>第二，使用通用视图更有力的方式是继承已存在的视图并覆盖子类里的属性（比如 <code class="docutils literal notranslate"><span class="pre">template_name</span></code> ）或方法（比如 <code class="docutils literal notranslate"><span class="pre">get_context_data</span></code> ）来提供新的值或方法。例如，考虑只显示一个 <code class="docutils literal notranslate"><span class="pre">about.html</span></code> 模板的视图。Django 的 <a class="reference internal" href="../../ref/class-based-views/base.html#django.views.generic.base.TemplateView" title="django.views.generic.base.TemplateView"><code class="xref py py-class docutils literal notranslate"><span class="pre">TemplateView</span></code></a> 可以完成这个工作，因此我们可以将其子类化并重写模板名称：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># some_app/views.py</span>
<span class="kn">from</span> <span class="nn">django.views.generic</span> <span class="kn">import</span> <span class="n">TemplateView</span>

<span class="k">class</span> <span class="nc">AboutView</span><span class="p">(</span><span class="n">TemplateView</span><span class="p">):</span>
    <span class="n">template_name</span> <span class="o">=</span> <span class="s2">&quot;about.html&quot;</span>
</pre></div>
</div>
<p>最后我们需要在 URLconf 中添加这个新视图。<a class="reference internal" href="../../ref/class-based-views/base.html#django.views.generic.base.TemplateView" title="django.views.generic.base.TemplateView"><code class="xref py py-class docutils literal notranslate"><span class="pre">TemplateView</span></code></a> 只是一个类，而不是一个函数，因此我们将 URL 指向 <a class="reference internal" href="../../ref/class-based-views/base.html#django.views.generic.base.View.as_view" title="django.views.generic.base.View.as_view"><code class="xref py py-meth docutils literal notranslate"><span class="pre">as_view()</span></code></a> ，它为基于类的视图提供一个类似函数的入口：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># urls.py</span>
<span class="kn">from</span> <span class="nn">django.urls</span> <span class="kn">import</span> <span class="n">path</span>
<span class="kn">from</span> <span class="nn">some_app.views</span> <span class="kn">import</span> <span class="n">AboutView</span>

<span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
    <span class="n">path</span><span class="p">(</span><span class="s1">&#39;about/&#39;</span><span class="p">,</span> <span class="n">AboutView</span><span class="o">.</span><span class="n">as_view</span><span class="p">()),</span>
<span class="p">]</span>
</pre></div>
</div>
<p>有关如何使用内建通用视图的更多信息，请查阅在 <a class="reference internal" href="generic-display.html"><span class="doc">generic class-based views</span></a> 的下一个主题。</p>
<div class="section" id="s-supporting-other-http-methods">
<span id="s-id1"></span><span id="supporting-other-http-methods"></span><span id="id1"></span><h3>支持其他 HTTP 方法<a class="headerlink" href="#supporting-other-http-methods" title="永久链接至标题">¶</a></h3>
<p>如果某人想将视图作为 API 来访问图书馆。API 客户端会时不时地连接并下载上次访问过后出版的书籍数据。但如果没有新的书籍出现，那么从数据库中获取书籍，渲染一个完整响应并发送它到客户端的话，这将浪费CPU时间和带宽。当出版最新的书时，它访问 API 最好。</p>
<p>我们需要在 URLconf 中映射 URL 到书籍列表视图：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.urls</span> <span class="kn">import</span> <span class="n">path</span>
<span class="kn">from</span> <span class="nn">books.views</span> <span class="kn">import</span> <span class="n">BookListView</span>

<span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
    <span class="n">path</span><span class="p">(</span><span class="s1">&#39;books/&#39;</span><span class="p">,</span> <span class="n">BookListView</span><span class="o">.</span><span class="n">as_view</span><span class="p">()),</span>
<span class="p">]</span>
</pre></div>
</div>
<p>还有视图：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.http</span> <span class="kn">import</span> <span class="n">HttpResponse</span>
<span class="kn">from</span> <span class="nn">django.views.generic</span> <span class="kn">import</span> <span class="n">ListView</span>
<span class="kn">from</span> <span class="nn">books.models</span> <span class="kn">import</span> <span class="n">Book</span>

<span class="k">class</span> <span class="nc">BookListView</span><span class="p">(</span><span class="n">ListView</span><span class="p">):</span>
    <span class="n">model</span> <span class="o">=</span> <span class="n">Book</span>

    <span class="k">def</span> <span class="nf">head</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="n">last_book</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_queryset</span><span class="p">()</span><span class="o">.</span><span class="n">latest</span><span class="p">(</span><span class="s1">&#39;publication_date&#39;</span><span class="p">)</span>
        <span class="n">response</span> <span class="o">=</span> <span class="n">HttpResponse</span><span class="p">(</span>
            <span class="c1"># RFC 1123 date format.</span>
            <span class="n">headers</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;Last-Modified&#39;</span><span class="p">:</span> <span class="n">last_book</span><span class="o">.</span><span class="n">publication_date</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%a</span><span class="s1">, </span><span class="si">%d</span><span class="s1"> %b %Y %H:%M:%S GMT&#39;</span><span class="p">)},</span>
        <span class="p">)</span>
        <span class="k">return</span> <span class="n">response</span>
</pre></div>
</div>
<p>如果从 <code class="docutils literal notranslate"><span class="pre">GET</span></code> 请求访问视图，将在响应（使用 <code class="docutils literal notranslate"><span class="pre">book_list.html</span></code> 模板）中返回一个干净的对象列表。但如果客户端发出一个 <code class="docutils literal notranslate"><span class="pre">HEAD</span></code> 请求，那么将响应一个空 body 和 <code class="docutils literal notranslate"><span class="pre">Last-Modified</span></code> 头将标识最新书籍的出版时间。基于这些信息，客户端可以选择是否下载一个完整的对象类。</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">基于类的视图</a><ul>
<li><a class="reference internal" href="#basic-examples">基础示例</a></li>
<li><a class="reference internal" href="#usage-in-your-urlconf">在 URLconf 中的用法</a></li>
<li><a class="reference internal" href="#subclassing-generic-views">子类化通用视图</a><ul>
<li><a class="reference internal" href="#supporting-other-http-methods">支持其他 HTTP 方法</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="../templates.html"
                        title="上一章">模板</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="intro.html"
                        title="下一章">基于类的视图</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../../_sources/topics/class-based-views/index.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">12月 07, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="../templates.html" title="模板">previous</a>
     |
    <a href="../index.html" title="使用 Django" accesskey="U">up</a>
   |
    <a href="intro.html" title="基于类的视图">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>